<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="vue contentEditable 与 selection&amp;range"><meta name="keywords" content=""><meta name="author" content="晟松"><meta name="copyright" content="晟松"><title>vue contentEditable 与 selection&amp;range | 晟松</title><link rel="shortcut icon" href="/logo.png"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?c34d81d53341febe06a155941e2df16d";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '5.4.0'
} </script><meta name="generator" content="Hexo 5.4.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E9%9C%80%E6%B1%82"><span class="toc-number">1.</span> <span class="toc-text">需求</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%9D%E8%B7%AF"><span class="toc-number">2.</span> <span class="toc-text">思路</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%E6%98%BE%E7%A4%BA%E8%87%AA%E5%AE%9A%E4%B9%89%E6%A0%B7%E5%BC%8F"><span class="toc-number">2.1.</span> <span class="toc-text">变量显示自定义样式</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%8E%A7%E5%88%B6%E8%BE%93%E5%85%A5"><span class="toc-number">2.2.</span> <span class="toc-text">控制输入</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E4%B8%AD%E6%96%87%E8%BE%93%E5%85%A5%E6%B3%95"><span class="toc-number">2.2.1.</span> <span class="toc-text">中文输入法</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%89%E6%A0%87%E5%AE%9A%E4%BD%8D"><span class="toc-number">2.3.</span> <span class="toc-text">光标定位</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#%E5%8F%A6%E5%A4%96%E4%B8%80%E4%B8%AA%E9%97%AE%E9%A2%98"><span class="toc-number">2.3.1.</span> <span class="toc-text">另外一个问题</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%85%83%E7%B4%A0%E9%80%89%E6%8B%A9"><span class="toc-number">2.4.</span> <span class="toc-text">元素选择</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E8%8A%82%E7%82%B9%E9%80%89%E6%8B%A9"><span class="toc-number">2.5.</span> <span class="toc-text">节点选择</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%82%E8%80%83%E6%96%87%E7%AB%A0"><span class="toc-number">3.</span> <span class="toc-text">参考文章</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="/img/avatar.png"></div><div class="author-info__name text-center">晟松</div><div class="author-info__description text-center">晟松的博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://gitee.com/cheng_song">Gitee</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">52</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">45</span></a></div></div></div><div id="content-outer"><div id="top-container" style="background-image: url(/img/blog-bg.jpg)"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">晟松</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">Home</a><a class="site-page" href="/archives">Archives</a><a class="site-page" href="/tags">Tags</a><a class="site-page" href="/categories">Categories</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">vue contentEditable 与 selection&amp;range</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2023-03-15</time><div class="post-meta-wordcount"><span>字数总计: </span><span class="word-count">3k</span><span class="post-meta__separator">|</span><span>阅读时长: 11 分钟</span></div></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><h3 id="需求"><a href="#需求" class="headerlink" title="需求"></a>需求</h3><p>类似一个公式编辑器，然后在这里面可以选择一些变量和一些运行符号，同时也可以自己输入这些符号与数字，最终进行展示。</p>
<p><img src="https://gitee.com/cheng_song/picgo-img/raw/master/img/image-20230318192100831.png"></p>
<p>先分析一下这个需要那些注意的点</p>
<ol>
<li>可以点击左侧变量，自动加入右侧编辑框，同时显示的样式需要变化</li>
<li>运算符号同理</li>
<li>可以自己输入数字0-9和+ - * / ( ) 符号</li>
<li>其他的不准输入</li>
</ol>
<p>看到这一块，人就有点麻了，然后去找了个相似的，灵珑的公式编辑是咋做的，然后感觉这有点像，但是又不满足我这边的注意点4，需要控制输入，然后找来找去，最后决定还是自己仿照这种tinymce的搞一个简要版满足需求的得了，然后就是一堆遇见问题，解决问题的过程了。虽然目前已经做了个大部分，但肯定有一些小bug在里面，不好找出来。。。</p>
<p><img src="https://gitee.com/cheng_song/picgo-img/raw/master/img/image-20230318192942094.png"></p>
<p>代码仓库地址：<a target="_blank" rel="noopener" href="http://192.168.101.70:8000/csgl/frontend/star-scales-v22-vue.git">http://192.168.101.70:8000/csgl/frontend/star-scales-v22-vue.git</a></p>
<p>src\pages\IndustryEvaluation\evaluationScheme\indexManage\add\components\formula</p>
<h3 id="思路"><a href="#思路" class="headerlink" title="思路"></a>思路</h3><p>核心：div + contenteditable=”true” + v-html</p>
<p>因为存在变量特殊显示，所以不能直接用input textarea这些原生组件，只能自己搞一个div，然后在里面控制自己的输入操作和变量显示</p>
<p>涉及到的一些技术点</p>
<ul>
<li>变量如何显示成自定义的样式</li>
<li>如何控制输入，包括特殊一点的中文输入</li>
<li>对一些组合按键事件，特殊处理</li>
<li>变量与运算符删除怎么删（这个东西由浏览器策略自己处理了，目前不用管）</li>
<li>光标定位怎么定位</li>
<li>点击变量或运算符号，这个变量需要怎么加到这个div里面去，同时加到目前光标的位置</li>
<li>div里面内容的选择与变量点击处理</li>
</ul>
<p>下面一个一个的来看哈</p>
<p>总的html与监听</p>
<figure class="highlight html"><table><tr><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">div</span></span></span><br><span class="line"><span class="tag">    <span class="attr">ref</span>=<span class="string">&quot;htmlHtmlContentRef&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">class</span>=<span class="string">&quot;htmlHtmlContent&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">contenteditable</span>=<span class="string">&quot;true&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">data-placeholder</span>=<span class="string">&quot;请配置公式&quot;</span></span></span><br><span class="line"><span class="tag">    @<span class="attr">input</span>=<span class="string">&quot;editorInput&quot;</span></span></span><br><span class="line"><span class="tag">    @<span class="attr">keydown</span>=<span class="string">&quot;handleKeyDown&quot;</span></span></span><br><span class="line"><span class="tag">    @<span class="attr">compositionstart</span>=<span class="string">&quot;handleStart&quot;</span></span></span><br><span class="line"><span class="tag">    @<span class="attr">compositionupdate</span>=<span class="string">&quot;handleupdate&quot;</span></span></span><br><span class="line"><span class="tag">    @<span class="attr">compositionend</span>=<span class="string">&quot;handleEnd&quot;</span></span></span><br><span class="line"><span class="tag">    <span class="attr">v-html</span>=<span class="string">&quot;htmlHtmlContent&quot;</span></span></span><br><span class="line"><span class="tag">&gt;</span><span class="tag">&lt;/<span class="name">div</span>&gt;</span></span><br></pre></td></tr></table></figure>



<h4 id="变量显示自定义样式"><a href="#变量显示自定义样式" class="headerlink" title="变量显示自定义样式"></a>变量显示自定义样式</h4><p>这一块，使用的是v-html进行显示，对于变量来说，直接变量包一个span标签，然后加一个class就行了，对于运算符号也同理。对于自己输入的运算符需要后面再进行处理。当前，为了把这一块当做一个整体，这个得<strong>设置 contentEditable = “false”</strong></p>
<h4 id="控制输入"><a href="#控制输入" class="headerlink" title="控制输入"></a>控制输入</h4><p>主要为监听input事件与keydown事件，input事件可以先不用管，keydown事件即当前在这个div里面按下的哪个键，这里根据需求整理的键有下面这一些，主要是0-9+运算符+删除+方向键+组合按键</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">/** 其他的一些特殊的操作keydown */</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> otherEnSureKey = [<span class="string">&#x27;Backspace&#x27;</span>, <span class="string">&#x27;Delete&#x27;</span>, <span class="string">&#x27;ArrowUp&#x27;</span>, <span class="string">&#x27;ArrowDown&#x27;</span>, <span class="string">&#x27;ArrowLeft&#x27;</span>, <span class="string">&#x27;ArrowRight&#x27;</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 单纯被允许的一些输入字符 */</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> constPureEnSureKey = [<span class="string">&#x27;0&#x27;</span>, <span class="string">&#x27;1&#x27;</span>, <span class="string">&#x27;2&#x27;</span>, <span class="string">&#x27;3&#x27;</span>, <span class="string">&#x27;4&#x27;</span>, <span class="string">&#x27;5&#x27;</span>, <span class="string">&#x27;6&#x27;</span>, <span class="string">&#x27;7&#x27;</span>, <span class="string">&#x27;8&#x27;</span>, <span class="string">&#x27;9&#x27;</span>, <span class="string">&#x27;+&#x27;</span>, <span class="string">&#x27;-&#x27;</span>, <span class="string">&#x27;*&#x27;</span>, <span class="string">&#x27;/&#x27;</span>, <span class="string">&#x27;(&#x27;</span>, <span class="string">&#x27;)&#x27;</span>];</span><br><span class="line"><span class="comment">/** 允许输入的keydown值，注意全部是字符串 */</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> constEnSureKey = constPureEnSureKey.concat(otherEnSureKey);</span><br><span class="line"></span><br><span class="line"><span class="comment">/** 需要与ctrl配合起来来做一些事情的keydown  &#x27;c&#x27;, &#x27;v&#x27; 先不开启了 */</span></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> constSpecialEnSureKey = [<span class="string">&#x27;Control&#x27;</span>, <span class="string">&#x27;a&#x27;</span>, <span class="string">&#x27;z&#x27;</span>, <span class="string">&#x27;y&#x27;</span>];</span><br><span class="line"></span><br></pre></td></tr></table></figure>



<p>对应的事件处理函数，在这里面，我们获取当前按下的键盘的键，然后判断这个键是否是允许输入的。允许，就自己**通过函数 addItemFormula **加到div里面，注意要preventDefault阻止默认事件。然后对于组合按键，就判断是不是目前允许的ctrl+a/z/y这几个就行了，对于删除和移动方向的键，默认事件的阻止似乎没用，也没必要。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 监听div里面的keydown即输入事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> </span>keydown 按钮按下事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;*&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">handleKeyDown</span>(<span class="params">keydown: any</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> curCodeKey = keydown.key;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 如果是一些组合事件，就允许进行操作，如ctrl+a...</span></span><br><span class="line">    <span class="keyword">if</span> (keydown.ctrlKey &amp;&amp; constSpecialEnSureKey.includes(curCodeKey)) <span class="keyword">return</span>;</span><br><span class="line">    <span class="keyword">if</span> (!constEnSureKey.includes(curCodeKey)) &#123;</span><br><span class="line">        <span class="comment">// 阻止默认的输入事件，让div里面没有其他的数据</span></span><br><span class="line">        keydown.preventDefault();</span><br><span class="line">        <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 如果是被允许的字段，就给加进去</span></span><br><span class="line">    <span class="keyword">if</span> (constPureEnSureKey.includes(curCodeKey)) &#123;</span><br><span class="line">        <span class="comment">// 阻止默认的输入事件，自己手动处理输入的数据</span></span><br><span class="line">        keydown.preventDefault();</span><br><span class="line">        addItemFormula(&#123; <span class="attr">name</span>: curCodeKey &#125;);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h5 id="中文输入法"><a href="#中文输入法" class="headerlink" title="中文输入法"></a>中文输入法</h5><p>主要利用下面几个事件compositionstart、compositionupdate、compositionend与input事件。这里最简单的方法就是在input的时候直接把当前中文输入法的数据不准输进去，然后剩下的关于光标的处理，后面再细说</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line">@input=<span class="string">&quot;editorInput&quot;</span></span><br><span class="line">@compositionstart=<span class="string">&quot;handleStart&quot;</span></span><br><span class="line">@compositionupdate=<span class="string">&quot;handleupdate&quot;</span></span><br><span class="line">@compositionend=<span class="string">&quot;handleEnd&quot;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 监听中文输入法的一些事件</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> <span class="variable">e</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">handleStart</span>(<span class="params">e: any</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 在中文输入法一开始就收集之前的数据，方便输入法结束的时候重置</span></span><br><span class="line">    getHtmlContentHtmlStr();</span><br><span class="line">    e.preventDefault();</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 这个触发有点问题，有时候不会进行触发，这里只能就直接在input事件里面处理了</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> <span class="variable">e</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">handleEnd</span>(<span class="params">e: any</span>) </span>&#123;</span><br><span class="line">    e.preventDefault();</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">handleupdate</span>(<span class="params">e: any</span>) </span>&#123;</span><br><span class="line">    e.preventDefault();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">editorInput</span>(<span class="params">e: any</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> inputData = e.data;</span><br><span class="line">    <span class="comment">// 这种方式，直接就禁用了中文输入法的感觉</span></span><br><span class="line">    <span class="keyword">if</span> (inputData &amp;&amp; !constPureEnSureKey.includes(inputData)) &#123;</span><br><span class="line">        <span class="comment">// 更新v-html</span></span><br><span class="line">        handleUpdateHtmlContentStr();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>参考：<a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Element/compositionstart_event">compositionstart - Web API 接口参考 | MDN (mozilla.org)</a></p>
<h4 id="光标定位"><a href="#光标定位" class="headerlink" title="光标定位"></a>光标定位</h4><p>这一块是最麻烦的一块东西，主要涉及这两个对象：selection和range。有了光标定位，那么后面的变量删除，变量选择，变量新增都可以迎刃而解。</p>
<p><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Selection">Selection - Web API 接口参考 | MDN (mozilla.org)</a></p>
<p><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Range">Range - Web API 接口参考 | MDN (mozilla.org)</a></p>
<p>首先解释一些这两个对象</p>
<p><strong>selection对象</strong>，主要是表示用户选择的文本范围或<strong>插入符号的当前位置</strong>，主要通过这个定位光标</p>
<p><code>getSelection()</code> 方法暴露在 document 和 window 对象上，返回当前选中文本的 Selection 对象。</p>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 获取 Selection 对象</span></span><br><span class="line"><span class="keyword">const</span> selection = <span class="built_in">window</span>.getSelection()</span><br></pre></td></tr></table></figure>

<p> <strong>Selection 对象用到的属性：</strong></p>
<ul>
<li><p> <strong>getRangeAt</strong>: 获取当前选区的range对象</p>
</li>
<li><p> <strong>selectAllChildren</strong>: 选择当前节点下面的所有子内容</p>
</li>
<li><p> <strong>collapseToEnd</strong>: 取消当前选区，并把光标定位在原选区的最末尾处，通过这个移动光标</p>
</li>
<li><p><strong>anchorNode：</strong> 锚点（<code>anchor</code>）所在节点。</p>
</li>
</ul>
<p>例：移动光标至一个节点的最后面，注意，这里移动的光标也在这个curDom里面，如果键盘输入的话，会发现输入的text是加到curDom HTMLElement内部的</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 光标移至一个元素的最后面</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;HTMLElement&#125;</span> </span>curDom editable元素</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;*&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">keepLastIndex</span>(<span class="params">curDom: HTMLElement</span>) </span>&#123;</span><br><span class="line">    nextTick(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        curDom.focus(); <span class="comment">// 解决ff不获取焦点无法定位问题</span></span><br><span class="line">        <span class="keyword">const</span> curSelection = <span class="built_in">window</span>.getSelection(); <span class="comment">// 创建 selection</span></span><br><span class="line">        curSelection?.selectAllChildren(curDom); <span class="comment">// selection 选择 curDom 下所有子内容</span></span><br><span class="line">        curSelection?.collapseToEnd(); <span class="comment">// 光标移至最后</span></span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>





<p><strong>range对象</strong>表示一个包含节点与文本节点的一部分的文档片段。就是下面这一块蓝色的东西，有时候通过这个对象，添加一些节点进去</p>
<p>而range对象表示一个包含节点与文本节点的一部分的文档片段。就是下面这一块蓝色的东西，有时候通过这个对象，添加一些节点进去</p>
<p><strong>用到的属性：</strong><br> <strong>insertNode</strong>: 从当前的range起始位置插入一个原生html Node节点</p>
<p><img src="https://gitee.com/cheng_song/picgo-img/raw/master/img/image-20230318204552793.png" alt="image-20230318204552793"></p>
<h5 id="另外一个问题"><a href="#另外一个问题" class="headerlink" title="另外一个问题"></a>另外一个问题</h5><p>试着想一下，两个span元素（设置了contentEditable false）之间没有其他的元素，如果把光标移至这两个span的中间，这个光标会显示成什么样。</p>
<p>结果是，你没办法把光标移进去</p>
<p>正常来说应该这样，中间有个光标在闪。</p>
<p><img src="https://gitee.com/cheng_song/picgo-img/raw/master/img/image-20230318210248005.png" alt="image-20230318210248005"></p>
<p>所以这就需要我们在这两个span元素中间再加一个空的span，不设置contentEditable，这个时候，光标就可以移到这个span元素内部，进行闪烁显示。类似这样，当然中间只要是空span，多几个也没啥影响</p>
<p><img src="https://gitee.com/cheng_song/picgo-img/raw/master/img/image-20230318212634302.png" alt="image-20230318212634302"></p>
<p>好，现在光标定位的问题解决了，那么就开始解决之前提出的一些问题，如何在当前点新增一个元素</p>
<p>理一下新增节点的流程：首先点击左侧变量，然后获取当前光标是定位在哪个元素，然后把创建的变量span元素加到当前光标定位的元素<strong>后面</strong>，然后补两个空span到变量的span前后，最后把光标移至最后一个空span。</p>
<p>注意里面的insertAfter函数与isSelectionInHtmlContainer的判断，当第一次添加元素的时候，直接使用<strong>range</strong>对象进行添加即可，因为<strong>现在定位的anchorNode</strong>为最开始的div元素。</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 在元素后插入新元素</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">insertAfter</span>(<span class="params">newElement: any, targetElement: &#123; parentNode: any; nextSibling: any &#125;</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> parent = targetElement.parentNode;</span><br><span class="line">    <span class="keyword">if</span> (parent.lastChild === targetElement) &#123;</span><br><span class="line">        parent.appendChild(newElement);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        parent.insertBefore(newElement, targetElement.nextSibling);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 个htmlstr添加到对应光标的位置</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> </span>htmlStr 添加的指标属性和运算符号</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;*&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">addHtmlNode</span>(<span class="params">node: HTMLElement</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 获取当前光标的位置，这里还得判断一下是不是在输入框里面才能添加</span></span><br><span class="line">    <span class="keyword">let</span> mineRange = selection?.getRangeAt(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 是否是光标监听到最外围的htmlHtmlContentRef了，一般只在初始添加时会出现</span></span><br><span class="line">    <span class="keyword">const</span> isSelectionInHtmlContainer = selection?.anchorNode === htmlHtmlContentRef.value;</span><br><span class="line">    <span class="keyword">if</span> (selection?.anchorNode?.parentElement !== htmlHtmlContentRef.value &amp;&amp; !isSelectionInHtmlContainer) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 注意在str的最后面还有一个空span，使得可以出现输入光标，主要这里inser的顺序，先是空span</span></span><br><span class="line">    <span class="keyword">const</span> nowEmptySpan = emptySpan();</span><br><span class="line">    <span class="comment">// 如果不是第一次添加，name就添加到目前的selection?.anchorNode元素的后面</span></span><br><span class="line">    <span class="keyword">if</span> (allSpanElement.value.length &gt; <span class="number">1</span> &amp;&amp; !isSelectionInHtmlContainer) &#123;</span><br><span class="line">        <span class="comment">// 前后添加一个空span，实现光标可见</span></span><br><span class="line">        insertAfter(nowEmptySpan, selection?.anchorNode <span class="keyword">as</span> Node);</span><br><span class="line">        insertAfter(node, selection?.anchorNode <span class="keyword">as</span> Node);</span><br><span class="line">        <span class="comment">// insertAfter(emptySpan(), selection?.anchorNode as Node);</span></span><br><span class="line">        <span class="comment">// 再次聚焦光标焦点</span></span><br><span class="line">        keepLastIndex(nowEmptySpan);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="comment">// 是第一次添加，就添加到htmlHtmlContentRef的里面去</span></span><br><span class="line">        mineRange?.insertNode(nowEmptySpan);</span><br><span class="line">        <span class="comment">// 在起始光标后面添加元素</span></span><br><span class="line">        mineRange?.insertNode(node);</span><br><span class="line">        <span class="comment">// 再加一个span用于实现光标的可选</span></span><br><span class="line">        mineRange?.insertNode(emptySpan());</span><br><span class="line">        <span class="comment">// 再次聚焦光标焦点</span></span><br><span class="line">        keepLastIndex(nowEmptySpan);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>而insertAfter是为了防止出现span元素嵌套的现象，类似这种</p>
<p><img src="https://gitee.com/cheng_song/picgo-img/raw/master/img/image-20230318215443359.png" alt="image-20230318215443359"></p>
<h4 id="元素选择"><a href="#元素选择" class="headerlink" title="元素选择"></a>元素选择</h4><p>这一块，主要是针对，之前创建的节点都是不可选的，如果想要把光标给移动位置，只能选择中间的空span，而不能点击自己创建的变量span，然后跳转光标，然后再进行删除等操作。类似如此，然后再点击了其他区域，再取消之前的选中状态</p>
<p><img src="https://gitee.com/cheng_song/picgo-img/raw/master/img/image-20230318215711150.png" alt="image-20230318215711150"></p>
<p>span.dataset.formulaSelect与 scss [data-formula-select] 相对应</p>
<figure class="highlight js"><table><tr><td class="code"><pre><span class="line"><span class="comment">// 添加点击事件，实现点击选中的样式效果，目前只有属性节点可以点击进行操作</span></span><br><span class="line">useEventListener(span, <span class="string">&#x27;click&#x27;</span>, <span class="function">(<span class="params">e</span>) =&gt;</span> &#123;</span><br><span class="line">    e.stopPropagation();</span><br><span class="line">    clearSpanDataSet(span);</span><br><span class="line">    <span class="keyword">if</span> (span.dataset.formulaSelect) &#123;</span><br><span class="line">        <span class="keyword">delete</span> span.dataset.formulaSelect;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        span.dataset.formulaSelect = <span class="string">&#x27;1&#x27;</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    selectionRangeToSpanAfter(span);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@description</span>: 点击其他地方清除span的选中效果</span></span><br><span class="line"><span class="comment"> * <span class="doctag">@param <span class="type">&#123;*&#125;</span> <span class="variable">document</span></span></span></span><br><span class="line"><span class="comment"> * <span class="doctag">@return <span class="type">&#123;*&#125;</span></span></span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line">useEventListener(<span class="built_in">document</span>, <span class="string">&#x27;click&#x27;</span>, <span class="function">(<span class="params">e</span>) =&gt;</span> &#123;</span><br><span class="line">    clearSpanDataSet();</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<figure class="highlight scss"><table><tr><td class="code"><pre><span class="line"></span><br><span class="line"><span class="selector-class">.htmlHtmlContent</span> &#123;</span><br><span class="line">    <span class="attribute">height</span>: <span class="number">200px</span>;</span><br><span class="line">    <span class="attribute">overflow-y</span>: auto;</span><br><span class="line">    <span class="attribute">padding</span>: <span class="number">10px</span>;</span><br><span class="line">    <span class="attribute">border</span>: <span class="number">1px</span> solid <span class="number">#e9ecf2</span>;</span><br><span class="line">    <span class="attribute">border-radius</span>: <span class="number">4px</span>;</span><br><span class="line">    <span class="attribute">background</span>: <span class="number">#000000</span>00;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 需要里面没有任何数据，目前里面还存在一个空格，还不行</span></span><br><span class="line">    &amp;<span class="selector-pseudo">:empty</span><span class="selector-pseudo">::after</span> &#123;</span><br><span class="line">        <span class="attribute">content</span>: attr(data-placeholder);</span><br><span class="line">        <span class="attribute">color</span>: <span class="number">#a8b4c8</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    &amp;<span class="selector-pseudo">:hover</span> &#123;</span><br><span class="line">        <span class="attribute">border</span>: solid <span class="number">1px</span> <span class="number">#3388ff</span>;</span><br><span class="line">        <span class="attribute">border-radius</span>: <span class="number">4px</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    &amp;<span class="selector-pseudo">:focus</span> &#123;</span><br><span class="line">        <span class="attribute">outline</span>: none;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    user-select: auto;</span><br><span class="line"></span><br><span class="line">    :deep(.operate-item) &#123;</span><br><span class="line">        display: inline-block;</span><br><span class="line">        <span class="attribute">height</span>: <span class="number">32px</span>;</span><br><span class="line">        <span class="attribute">line-height</span>: <span class="number">32px</span>;</span><br><span class="line">        <span class="attribute">margin</span>: <span class="number">0</span> <span class="number">5px</span> <span class="number">5px</span> <span class="number">5px</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    :deep(.property-item) &#123;</span><br><span class="line">        display: inline-block;</span><br><span class="line">        <span class="attribute">height</span>: <span class="number">32px</span>;</span><br><span class="line">        <span class="attribute">margin</span>: <span class="number">0</span> <span class="number">5px</span> <span class="number">5px</span> <span class="number">5px</span>;</span><br><span class="line">        <span class="attribute">background</span>: <span class="number">#e9ecf2</span>;</span><br><span class="line">        <span class="attribute">border-radius</span>: <span class="number">4px</span>;</span><br><span class="line">        <span class="attribute">padding</span>: <span class="number">6px</span> <span class="number">8px</span>;</span><br><span class="line">        <span class="attribute">font-weight</span>: <span class="number">400</span>;</span><br><span class="line">        <span class="attribute">font-size</span>: <span class="number">14px</span>;</span><br><span class="line">        <span class="selector-attr">[contentEditable=<span class="string">&#x27;false&#x27;</span>]</span> &#123;</span><br><span class="line">            <span class="attribute">cursor</span>: default;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 当被点击选择的时候，进行一下显示</span></span><br><span class="line">        &amp;<span class="selector-attr">[data-formula-select]</span> &#123;</span><br><span class="line">            <span class="attribute">cursor</span>: not-allowed;</span><br><span class="line">            <span class="attribute">outline</span>: <span class="number">3px</span> solid <span class="number">#3388ff</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>





<h4 id="节点选择"><a href="#节点选择" class="headerlink" title="节点选择"></a>节点选择</h4><p>这一块也主要是通过css进行控制  user-select: auto;主要是实现ctrl+a，全部标蓝进行提示，不然设置成none的话，就没有这个效果，就没这个蓝色提示了</p>
<p><img src="https://gitee.com/cheng_song/picgo-img/raw/master/img/image-20230318221057630.png" alt="image-20230318221057630"></p>
<h3 id="参考文章"><a href="#参考文章" class="headerlink" title="参考文章"></a>参考文章</h3><p><a target="_blank" rel="noopener" href="https://juejin.cn/post/6991834017825832974#heading-11">可以编辑的 DIV - 掘金 (juejin.cn)</a></p>
<p><a target="_blank" rel="noopener" href="https://juejin.cn/post/6976147434938302471">JavaScript中对光标和选区的操作 - 掘金 (juejin.cn)</a></p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">晟松</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://chengsong.info/2023/03/15/vue-contentEditable-与-selection-range/">https://chengsong.info/2023/03/15/vue-contentEditable-与-selection-range/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://chengsong.info">晟松</a>！</span></div></div><div class="post-meta__tag-list"></div><nav id="pagination"><div class="next-post pull-right"><a href="/2023/03/15/vue-iframe%E9%87%8D%E5%8A%A0%E8%BD%BD%E9%97%AE%E9%A2%98%E8%A7%A3%E5%86%B3/"><span>vue iframe重加载问题解决</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer class="footer-bg" style="background-image: url(/img/blog-bg.jpg)"><div class="layout" id="footer"><div class="copyright">&copy;2020 - 2023 By 晟松</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="icp"><a target="_blank" rel="noopener" href="http://www.beian.miit.gov.cn/"><span>湘ICP备2020021729号</span></a></div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>